// 和用户相关的状态管理
import { createSlice } from '@reduxjs/toolkit'
import { request } from '@/utils/request'
import { login } from '@/apis/login'
import { setToken as _setToken, getToken } from '@/utils/token'
const userStore = createSlice({
  name: "user",
  initialState: {
    token: getToken() || ''
  },
  reducers: {
    setToken(state, action) {
      state.token = action.payload
      // localStorage.setItem('token_key', action.payload)
      _setToken(action.payload)
    }
  }
})


const { setToken } = userStore.actions

const userReducer = userStore.reducer


const fetchLogin = (loginForm) => {
  return async (dispatch) => {
    console.log('测试:', loginForm);

    // 异步请求
    const { data } = await login(loginForm)

    //提交同步action进行token存入
    // console.log('token的值', res.data.data.token);
    // res.data被我取出来了
    console.log('12222', data.token);

    dispatch(setToken(data.token))

  }
}

export { fetchLogin, setToken }
export default userReducer